<template>
  <div class="app-container">
    <!-- 搜索 -->
    <el-card>
      <el-form :inline="true" :model="listQuery" size="small">
        <el-form-item>
          <el-input
            placeholder="商家名称"
            clearable
            v-model="listQuery.name"
            @keyup.enter.native="handleFilter"
          />
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-search"
            @click.native="handleFilter"
            >查询</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
          >
            新增{{ title }}
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="handleBatchDelete"
          >
            批量删除
          </el-button>
        </el-form-item>
      </el-form>

      <!-- table列表 -->
      <el-table
        style="width: 100%"
        border
        stripe
        size="small"
        :data="datas"
        v-loading="listLoading"
        highlight-current-row
        @selection-change="handleSelectionChange"
      >
        <el-table-column label="#" align="center" type="selection" />
        <el-table-column
          v-for="column in tableColumns"
          :key="column.key"
          :label="column.title"
          :prop="column.key"
          :align="column.align ? column.align : 'center'"
          :width="column.width ? column.width : ''"
        >
        </el-table-column>
        <el-table-column align="center" label="操作" width="200px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="handleEdit(scope)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="handleDelete(scope)"
              >删除</el-button
            >
            <!-- <el-button
              type="success"
              size="mini"
              icon="el-icon-upload"
              @click="handleUpload(scope)"
              >图片</el-button
            > -->
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.page_size"
        @pagination="getRetailerList"
      />
    </el-card>
    <!-- 弹框 -->
    <el-dialog :title="getTitle" :visible.sync="dialogVisible" width="50%">
      <el-form
        size="small"
        :model="form"
        :rules="formRules"
        ref="formRef"
        label-width="120px"
        label-position="right"
        style="width: 95%"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="商家名称" prop="name">
              <el-input v-model="form.name" placeholder="商家名称" clearable />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="商家地址" prop="address">
              <el-input
                v-model="form.address"
                placeholder="商家地址"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="微信ID" prop="openid">
              <el-input v-model="form.openid" placeholder="注册微信ID">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名/昵称" prop="boss_name">
              <el-input v-model="form.boss_name" placeholder="注册人姓名或昵称">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="telephone">
              <el-input
                v-model="form.telephone"
                placeholder="联系电话"
                clearable
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="会员确认" prop="flag">
              <el-select v-model="form.flag" placeholder="会员确认">
                <el-option
                  v-for="item in flags"
                  :label="item.label"
                  :value="item.value"
                  :key="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" size="small" @click="handleSave(false)"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <!-- 图片上传 -->
    <!-- <el-dialog
      :visible.sync="dlgUploadVisible"
      title="商家图片"
      width="800px"
      destroy-on-close
      @close="handleClose"
    >
      <el-form
        label-width="100px"
        :model="uploadForm"
        label-position="right"
        style="width: 95%; padding: 0 30px"
        status-icon
      >
        <el-form-item label="商家名称">
          <el-input v-model="uploadForm.name" size="small" disabled></el-input>
        </el-form-item>

        <el-form-item label="商家图片">
          <el-upload
            ref="upload"
            name="image"
            action="/api/member/image_upload/"
            multiple
            :on-preview="handlePreview"
            :before-upload="handleBeforeUpload"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
            :file-list="fileList"
            accept=".jpg, .jpeg, .png, .gif, .JPG, .JPEG, .PNG, .GIF"
            :headers="headerObj"
            :data="uploadData"
            list-type="picture-card"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dlgUploadVisible = false" size="mini"
          >关闭</el-button
        >
      </div>
      <el-dialog :visible.sync="dlgImageVisible" append-to-body>
        <el-image
          style="width: 100%; min-height: 400px"
          :src="dlgImageUrl"
          fit="fill"
        ></el-image>
        <div slot="footer">
          <el-button @click="dlgImageVisible = false" size="mini"
            >关闭</el-button
          >
        </div>
      </el-dialog>
    </el-dialog> -->
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import Pagination from "@/components/Pagination";
import { pickerOptions } from "@/utils/const";
import {
  getRetailers,
  addRetailer,
  updateRetailer,
  delRetailer,
  delRetailers,
  delRetailerImage,
} from "@/api/member";

const defaultForm = {
  id: null,
  name: null,
  address: null,
  openid: null,
  boss_name: "",
};

export default {
  name: "Retailer",
  data() {
    return {
      form: Object.assign({}, defaultForm),

      formRules: {
        name: [{ required: true, message: "请输入商家名称", trigger: "blur" }],
        address: [{ required: true, message: "请输入地址", trigger: "blur" }],
        telephone: [
          { required: true, message: "请输入联系电话", trigger: "blur" },
        ],
        openid: [
          { required: true, message: "请输入联系电话", trigger: "blur" },
        ],
        boss_name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
      },
      title: "商家",
      dialogType: "new",
      dialogVisible: false,
      dlgUploadVisible: false,

      datas: [],
      selections: [],
      uploadForm: {
        name: "",
        retailer_id: null,
        images: [],
      },
      fileList: [],
      dlgImageVisible: false,
      dlgImageUrl: "",

      listLoading: true,
      listQuery: {
        name: null,
        page: 1,
        page_size: 15,
      },
      total: 0,

      tableColumns: [
        {
          key: "name",
          title: "商家名称",
          align: "left",
        },

        {
          key: "address",
          title: "商家地址",
          align: "left",
        },

        {
          key: "telephone",
          title: "联系电话",
        },
        {
          key: "openid",
          title: "微信ID",
        },
        {
          key: "flag_name",
          title: "会员确认",
          width: "80",
        },
      ],
      flags: [
        { value: 0, label: "无效" },
        { value: 1, label: "生效" },
      ],
      pickerOptions,
    };
  },
  components: {
    Pagination,
  },
  computed: {
    ...mapGetters(["uid", "token"]),
    getTitle() {
      return this.dialogType == "new"
        ? `新增${this.title}`
        : `修改${this.title}`;
    },
    headerObj() {
      return {
        authorization: "JWT " + this.token,
      };
    },
    uploadData() {
      return {
        retailer_id: this.uploadForm.retailer_id,
      };
    },
  },
  created() {
    this.getRetailerList();
  },
  methods: {
    number() {
      this.form.price = this.form.merit.replace(/[^\d.]/g, "");
    },
    //
    getRetailerList() {
      this.listLoading = true;
      getRetailers(this.listQuery)
        .then((res) => {
          this.datas = res.results;
          this.total = res.count;
          this.listLoading = false;
        })
        .catch((err) => {
          this.listLoading = false;
          this.$message.error("获取数据失败!");
        });
    },

    // 查询
    handleFilter() {
      this.listQuery.page = 1;
      this.getRetailerList();
    },
    //添加
    handleAdd() {
      this.dialogVisible = true;
      this.dialogType = "new";
      this.form = Object.assign({}, defaultForm);
      this.$nextTick(() => {
        this.$refs.formRef.clearValidate();
      });
    },
    //修改
    handleEdit(scope) {
      this.dialogType = "edit";
      this.form = scope.row;
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.formRef.clearValidate();
      });
    },
    //确定添加数据
    async handleSave() {
      this.$refs.formRef.validate(async (valid) => {
        if (!valid) return;

        let res = null;
        if (this.dialogType == "new") {
          this.form.user = this.uid;
          try {
            res = await addRetailer(this.form);
          } catch (err) {
            this.$message.error("增加失败!");
          }
        } else {
          if (!this.form.user) {
            this.form.user = this.uid;
          }
          try {
            res = await updateRetailer(this.form);
          } catch (err) {
            // console.log(err);
            this.$message.error("修改失败!");
          }
        }

        this.dialogVisible = false;
        this.getRetailerList();

        const { name, address, person, telephone } = res;

        this.$notify({
          title: "Success",
          dangerouslyUseHTMLString: true,
          message: `
              <div>商家名称: ${name}</div>
              <div>信用代码: ${code}</div>
              <div>商家地址: ${address}</div>
              <div>联系人: ${person}</div>
              <div>联系电话: ${telephone}</div>
            `,
          type: "success",
        });
      });
    },
    //弹窗显示，数据回显

    //删除数据
    handleDelete({ $index, row }) {
      this.$confirm("确定要删除吗?", "删除提示：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await delRetailer(row.id);
          this.datas.splice($index, 1);
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((err) => {
          console.error(err);
        });
    },
    handleBatchDelete() {
      if (this.selections.length == 0) {
        this.$message.warning("请选择要删除记录");
        return;
      }
      this.$confirm("确定要删除选中记录吗?", "删除提示：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const sel_ids = {
            select_ids: this.selections,
          };
          const res = await delRetailers(sel_ids);
          this.getRetailerList();
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((err) => {
          console.error(err);
        });
    },
    handleSelectionChange(val) {
      this.selections = val.map((item) => item.id);
    },
    ///上传图片
    handleUpload(scope) {
      this.dlgUploadVisible = true;
      this.uploadForm.retailer_id = scope.row.id;
      this.uploadForm.name = scope.row.name;
      this.uploadForm.images = scope.row.images;

      this.fileList = this.uploadForm.images.map((item) => {
        return {
          name: item.name,
          url: item.image,
          id: item.id,
        };
      });
    },
    handleSuccess(res, file, filelist) {
      this.fileList = filelist;
      if (res.status_code == 200) {
        this.uploadForm.images.push(file.response.file);
        this.$message.success("图片上传成功");
      } else {
        this.$message.error("上传失败");
      }
    },
    //图片删除
    handleRemove(file, fileList) {
      this.fileList = fileList;
      var file_id = null;
      file_id = file.id;
      if (file_id == null) {
        if (file.response.status_code == 200) {
          file_id = file.response.file.id;
        }
      }

      if (file_id == null) return;

      delRetailerImage(file_id)
        .then((res) => {
          const index = this.uploadForm.images.findIndex(
            (item) => item.id == file_id
          );
          if (index > -1) {
            this.uploadForm.images.splice(index, 1);
          }
          this.$message.success("删除成功");
        })
        .catch((error) => {
          this.$message.error("删除失败");
        });
    },
    //上传前
    handleBeforeUpload(file) {
      const flag = file.size / 1024 / 1024 < 10;
      if (!flag) {
        this.$message.error("上传文件大小不能超过 10MB!");
      }
      return flag;
    },
    // 预览
    handlePreview(file) {
      this.dlgImageUrl = file.url;
      this.dlgImageVisible = true;
    },
    //关闭对话框
    handleClose() {
      this.fileList = [];
    },
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 2) {
          sums[index] = "合计";
          return;
        }
        if (column.property === "score") {
          const values = data.map((item) => item[column.property]);
          sums[index] = values
            .reduce((prev, curr) => {
              return prev + curr;
            }, 0)
            .toFixed(2);
          sums[index] = toThousandFilter(sums[index]);
          sums[index] += " 元";
        } else {
          return;
        }
      });

      return sums;
    },
  },
};
</script>

<style scoped>
</style>